package jnpf.service.impl;

import jnpf.entity.*;
import jnpf.mapper.AgentMapper;
import jnpf.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.model.agent.*;
import java.math.BigDecimal;
import cn.hutool.core.util.ObjectUtil;
import jnpf.permission.model.authorize.AuthorizeConditionModel;
import jnpf.util.GeneraterSwapUtil;
import jnpf.database.model.superQuery.SuperQueryJsonModel;
import jnpf.database.model.superQuery.ConditionJsonModel;
import jnpf.database.model.superQuery.SuperQueryConditionModel;
import java.lang.reflect.Field;
import com.baomidou.mybatisplus.annotation.TableField;
import java.util.regex.Pattern;
import jnpf.model.QueryModel;
import java.util.stream.Collectors;
import jnpf.base.model.ColumnDataModel;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import jnpf.database.model.superQuery.SuperJsonModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.text.SimpleDateFormat;
import jnpf.util.*;
import java.util.*;
import jnpf.base.UserInfo;
import jnpf.permission.entity.UserEntity;
/**
 *
 * agent
 * 版本： V3.5
 * 版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * 作者： JNPF开发平台组
 * 日期： 2025-05-25
 */
@Service
public class AgentServiceImpl extends ServiceImpl<AgentMapper, AgentEntity> implements AgentService{
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Override
    public List<AgentEntity> getList(AgentPagination agentPagination){
        return getTypeList(agentPagination,agentPagination.getDataType());
    }
    /** 列表查询 */
    @Override
    public List<AgentEntity> getTypeList(AgentPagination agentPagination,String dataType){
        String userId=userProvider.get().getUserId();
        List<String> AllIdList =new ArrayList();
        List<List<String>> intersectionList =new ArrayList<>();
        boolean isPc = ServletUtil.getHeader("jnpf-origin").equals("pc");
        String columnData = !isPc ? AgentConstant.getAppColumnData() : AgentConstant.getColumnData();
        ColumnDataModel columnDataModel = JsonUtil.getJsonToBean(columnData, ColumnDataModel.class);
        String ruleJson = !isPc ? JsonUtil.getObjectToString(columnDataModel.getRuleListApp()) : JsonUtil.getObjectToString(columnDataModel.getRuleList());

        int total=0;
        int agentNum =0;
        QueryWrapper<AgentEntity> agentQueryWrapper=new QueryWrapper<>();
        List<String> allSuperIDlist = new ArrayList<>();
        String superOp ="";
        if (ObjectUtil.isNotEmpty(agentPagination.getSuperQueryJson())){
            List<String> allSuperList = new ArrayList<>();
            List<List<String>> intersectionSuperList  = new ArrayList<>();
            String queryJson = agentPagination.getSuperQueryJson();
            SuperJsonModel superJsonModel = JsonUtil.getJsonToBean(queryJson, SuperJsonModel.class);
            int superNum = 0;
            QueryWrapper<AgentEntity> agentSuperWrapper = new QueryWrapper<>();
            agentSuperWrapper = generaterSwapUtil.getCondition(new QueryModel(agentSuperWrapper,AgentEntity.class,queryJson,"0"));
            int agentNum1 = agentSuperWrapper.getExpression().getNormal().size();
            if (agentNum1>0){
                List<String> agentList =this.list(agentSuperWrapper).stream().map(AgentEntity::getId).collect(Collectors.toList());
                allSuperList.addAll(agentList);
                intersectionSuperList.add(agentList);
                superNum++;
            }
            superOp = superNum > 0 ? superJsonModel.getMatchLogic() : "";
            //and or
            if(superOp.equalsIgnoreCase("and")){
                allSuperIDlist = generaterSwapUtil.getIntersection(intersectionSuperList);
            }else{
                allSuperIDlist = allSuperList;
            }
        }
        List<String> allRuleIDlist = new ArrayList<>();
        String ruleOp ="";
        if (ObjectUtil.isNotEmpty(ruleJson)){
            List<String> allRuleList = new ArrayList<>();
            List<List<String>> intersectionRuleList  = new ArrayList<>();
            SuperJsonModel ruleJsonModel = JsonUtil.getJsonToBean(ruleJson, SuperJsonModel.class);
            int ruleNum = 0;
            QueryWrapper<AgentEntity> agentSuperWrapper = new QueryWrapper<>();
            agentSuperWrapper = generaterSwapUtil.getCondition(new QueryModel(agentSuperWrapper,AgentEntity.class,ruleJson,"0"));
            int agentNum1 = agentSuperWrapper.getExpression().getNormal().size();
            if (agentNum1>0){
                List<String> agentList =this.list(agentSuperWrapper).stream().map(AgentEntity::getId).collect(Collectors.toList());
                allRuleList.addAll(agentList);
                intersectionRuleList.add(agentList);
                ruleNum++;
            }
            ruleOp = ruleNum > 0 ? ruleJsonModel.getMatchLogic() : "";
            //and or
            if(ruleOp.equalsIgnoreCase("and")){
                allRuleIDlist = generaterSwapUtil.getIntersection(intersectionRuleList);
            }else{
                allRuleIDlist = allRuleList;
            }
        }
    boolean pcPermission = false;
    boolean appPermission = false;
    if(isPc && pcPermission){
    if (!userProvider.get().getIsAdministrator()){
        Object agentObj=generaterSwapUtil.getAuthorizeCondition(new QueryModel(agentQueryWrapper,AgentEntity.class,agentPagination.getMenuId(),"0"));
        if (ObjectUtil.isEmpty(agentObj)){
        return new ArrayList<>();
        } else {
        agentQueryWrapper = (QueryWrapper<AgentEntity>)agentObj;
        if( agentQueryWrapper.getExpression().getNormal().size()>0){
        agentNum++;
        }
        }
    }
    }
    if(!isPc && appPermission){
    if (!userProvider.get().getIsAdministrator()){
        Object agentObj=generaterSwapUtil.getAuthorizeCondition(new QueryModel(agentQueryWrapper,AgentEntity.class,agentPagination.getMenuId(),"0"));
        if (ObjectUtil.isEmpty(agentObj)){
        return new ArrayList<>();
        } else {
        agentQueryWrapper = (QueryWrapper<AgentEntity>)agentObj;
        if( agentQueryWrapper.getExpression().getNormal().size()>0){
        agentNum++;
        }
        }


    }
    }
        if(isPc){
            if(ObjectUtil.isNotEmpty(agentPagination.getName())){
            agentNum++;

                String value = agentPagination.getName() instanceof List ?
                    JsonUtil.getObjectToString(agentPagination.getName()) :
                    String.valueOf(agentPagination.getName());
                agentQueryWrapper.lambda().like(AgentEntity::getName,value);

            }

        }
        List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
        if (total>0){
            if (intersection.size()==0){
                intersection.add("jnpfNullList");
            }
            agentQueryWrapper.lambda().in(AgentEntity::getId, intersection);
        }
    //是否有高级查询
        if (StringUtil.isNotEmpty(superOp)){
            if (allSuperIDlist.size()==0){
                allSuperIDlist.add("jnpfNullList");
            }
            List<String> finalAllSuperIDlist = allSuperIDlist;
            agentQueryWrapper.lambda().and(t->t.in(AgentEntity::getId, finalAllSuperIDlist));
        }
    //是否有数据过滤查询
        if (StringUtil.isNotEmpty(ruleOp)){
            if (allRuleIDlist.size()==0){
                allRuleIDlist.add("jnpfNullList");
            }
            List<String> finalAllRuleIDlist = allRuleIDlist;
            agentQueryWrapper.lambda().and(t->t.in(AgentEntity::getId, finalAllRuleIDlist));
        }

        //排序
        if(StringUtil.isEmpty(agentPagination.getSidx())){
            agentQueryWrapper.lambda().orderByDesc(AgentEntity::getId);
        }else{
            try {
                String sidx = agentPagination.getSidx();
                String[] strs= sidx.split("_name");
                AgentEntity agentEntity = new AgentEntity();
                Field declaredField = agentEntity.getClass().getDeclaredField(strs[0]);
                declaredField.setAccessible(true);
                String value = declaredField.getAnnotation(TableField.class).value();
                agentQueryWrapper="asc".equals(agentPagination.getSort().toLowerCase())?agentQueryWrapper.orderByAsc(value):agentQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }

        if("0".equals(dataType)){
            if((total>0 && AllIdList.size()>0) || total==0){
                Page<AgentEntity> page=new Page<>(agentPagination.getCurrentPage(), agentPagination.getPageSize());
                IPage<AgentEntity> userIPage=this.page(page, agentQueryWrapper);
                return agentPagination.setData(userIPage.getRecords(),userIPage.getTotal());
            }else{
                List<AgentEntity> list = new ArrayList();
                return agentPagination.setData(list, list.size());
            }
        }else{
            return this.list(agentQueryWrapper);
        }
    }
    @Override
    public AgentEntity getInfo(String id){
        QueryWrapper<AgentEntity> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(AgentEntity::getId,id);
        return this.getOne(queryWrapper);
    }
    @Override
    public void create(AgentEntity entity){
        this.save(entity);
    }
    @Override
    public boolean update(String id, AgentEntity entity){
        return this.updateById(entity);
    }
    @Override
    public void delete(AgentEntity entity){
        if(entity!=null){
            this.removeById(entity.getId());
        }
    }
    /** 验证表单唯一字段，正则，非空 i-0新增-1修改*/
    @Override
    public String checkForm(AgentForm form,int i) {
        boolean isUp =StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
        String id="";
        String countRecover = "";
        if (isUp){
            id = form.getId();
        }
        //主表字段验证
        return countRecover;
    }
    /**
    * 新增修改数据(事务回滚)
    * @param id
    * @param agentForm
    * @return
    */
    @Override
    @Transactional
    public AgentEntity saveOrUpdate(AgentForm agentForm,String id, boolean isSave) throws Exception{
        UserInfo userInfo=userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        agentForm = JsonUtil.getJsonToBean(
        generaterSwapUtil.swapDatetime(AgentConstant.getFormData(),agentForm),AgentForm.class);
        AgentEntity entity = JsonUtil.getJsonToBean(agentForm, AgentEntity.class);

        if(isSave){
            String mainId =  RandomUtil.uuId() ;
        entity.setCreateuserid(userInfo.getUserId());
        entity.setCreatetime(DateUtil.getNowDate());
            entity.setId(mainId);
        }else{
        entity.setCreateuserid(userInfo.getUserId());
        entity.setCreatetime(DateUtil.getNowDate());
        }
        this.saveOrUpdate(entity);
        return entity;
    }
}
